package com.mec.web.y2012.coreservlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.mec.beans.y2013.m03.FileUploadHandler;
import com.mec.web.y2013.WebXMLConfig2013;


/**
 *	refer to commons.apache.org/fileupload
 * @author MEC
 *
 */
@WebServlet(urlPatterns = {
				"/FileUploadServlet",
				"/2012/coreservlet/fileUpload.action"
				},
			initParams = {
				@WebInitParam(name = "forwardJsp", 
						value = "/WEB-INF/Date/2012/jsp/uploadFileFinished.jsp"
						)
			
			}
			)
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FileUploadServlet() {
        super();
    }
    
    
	@Override
	public void init() throws ServletException {
		int randSuffixLength = DEFAULT_RANDOM_SUFFIX_LENGTH;
		String randSuffixLengthStr = getServletConfig().getInitParameter(WebXMLConfig2013.USER_UPLOAD_FILE_RAND_SUFFIX_LENGTH);
		if(null != randSuffixLengthStr){
			try {
				randSuffixLength = Integer.parseInt(randSuffixLengthStr);
			} catch (NumberFormatException e) {
				logger.info("Parse Context Init Parameter error: ", e);
			}
		}
		
		ServletContext application = getServletContext();
		
		String parentDir = application.getRealPath("/");
		String serverPathOfFile = application.getInitParameter(WebXMLConfig2013.USER_UPLOAD_ROOT_PATH);
		handler = new FileUploadHandler(parentDir, serverPathOfFile, randSuffixLength);
	}



	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if(! isMultipart){
			String title = "Upload file failed";
			out.println(
					Constants.docType +
					ServletUtilities.headWithTitle(title) +
					"<body><h1>" + title + "<h1><p>" +
					"form.encType should be multipart/form-data and method should be post.</p></body></html>"
					);
			return;
		}
		//
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?>  items = upload.parseRequest(request);
			//logger.info("item.size ->" + items.toArray().length);
			if(null != items){
				for(Object item :items){
					FileItem fileItem = (FileItem) item;
					
					//
					if(fileItem.isFormField()){
						processFormField(fileItem);
					}else{
						handler.processUploadedFile(fileItem);
						request.setAttribute("referencePath", getServletContext().getContextPath() + handler.getUploadedFilePath());
					}
				}
			}
		} catch (FileUploadException fue) {
			logger.error("parse request parameter failed", fue);
		}catch(Exception e){
			logger.error("Process File failed: ", e);
		}
		//
			
		String forwardJsp = getInitParameter("forwardJsp");
		RequestDispatcher dispatcher = request.getRequestDispatcher(forwardJsp);
		dispatcher.forward(request, response);
		
		//out.println("");
		
	}
	
	private void processFormField(FileItem item){
		String name = item.getFieldName();
		String value = item.getString();
		
		logger.info("name -> " + name + ", value -> " + value);
		
	}
	
	
	
	private boolean isImage(String name){
		return name.endsWith(".JPEG") 
				|| name.endsWith(".JPG")
				|| name.endsWith(".PNG")
				|| name.endsWith(".GIF")
				|| name.endsWith(".BMP")
				;
	}
	
	
	private int DEFAULT_RANDOM_SUFFIX_LENGTH = 10; // default random string suffix length;
	
	
	private FileUploadHandler handler;
	private static final Logger logger = 
			Logger.getLogger(FileUploadServlet.class);

}